<template>
    <Upload ref="uploadRef" :multiple="props.setConfig.multiple" type="drag" :format="props.setConfig.accept"
        accept=".jpeg,.jpg" :before-upload="handleBeforeUpload" :disabled="props.setConfig.disabled">
        <div style="padding: 20px 0">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p style="font-size: 12px;">
                <span v-if="props.setConfig.size != '' || props.setConfig.size != 0">单文件大小最大为{{ props.setConfig.size }}MB </span>
                <span v-if="props.setConfig.limit != '' || props.setConfig.limit != 0">最多上传{{ props.setConfig.limit }}个文件</span>
            </p>
            <p style="font-size: 12px;" v-if="props.setConfig.accept && props.setConfig.accept.length">允许上传文件类型{{ getAcceptStr() }}</p>
            <p>点击或拖拽文件上传</p>
        </div>
    </Upload>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';

/**
 * @param {
 *      setConfig: {
 *          limit: '限制文件个数', // 默认为1个
 *          size: '文件大小限制' // 默认为500M
 *          multiple: '是否可选择多个文件'
 *          accept: '支持文件类型数组'
 *          disabled: '是否禁用'
 *      },
 *      modelValue: 双向绑定
 * }
 */
const props = defineProps({
    setConfig: {
        type: Object,
    },
    modelValue: {
        type: Array,
        default: []
    },
});

const emit = defineEmits(['update:modelValue']);

const { proxy } = getCurrentInstance();

// 上传组件ref
const uploadRef = ref();

// 获取文件类型字符串
const getAcceptStr = () => {
    return props.setConfig.accept.toString();
}

const handleBeforeUpload = (file) => {
    let maxSize = props.setConfig.size * 1024 * 1024;
    let fileType = file.name.split('.')[file.name.split('.').length - 1];
    if ((uploadRef.value.fileList.length >= props.setConfig.limit) && props.setConfig.limit != 0 && props.setConfig.limit) {
        proxy.$Message.error('超出文件限制个数!');
        return;
    }
    if ((file.size > maxSize) && maxSize != 0) {
        proxy.$Message.error(`文件大小不能超过 ${props.setConfig.size}MB`);
        return;
    }
    if (!props.setConfig.accept.includes(fileType)) {
        proxy.$Message.error(`请上传正确文件类型`);
        return;
    }
    uploadRef.value.fileList.push({
        name: file.name,
        percentage: 100,
        showProgress: false,
        response: file,
        size: file.size,
        status: 'finished',
        uid: file.uid
    });
    emit('update:modelValue', uploadRef.value.fileList);
    return false;
}

</script>